package com.kc.stand.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kc.stand.domain.Article;
import com.kc.stand.domain.FileManage;
import com.kc.stand.domain.StandFileList;
import com.kc.stand.service.ArticleService;
import com.kc.stand.service.FileManageService;
import com.kc.stand.service.StandFineListService;
import com.kc.stand.vo.StandFileListVo;
import com.kc.sys.common.*;
import com.kc.sys.domain.Station;
import com.kc.sys.domain.User;
import com.kc.sys.service.StationService;
import com.kc.sys.service.UserService;
import com.kc.sys.util.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 * 站细列表
 * @author 老杜
 * @since 2019-12-30
 */
@RestController
@RequestMapping("/standFineList")
public class FineListController {


    @Autowired
    private StandFineListService standFineListService;
    @Autowired
    private StationService stationService;
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private FileManageService fileManageService;
    /**
     * 查询
     */
    @RequestMapping("loadAllStandFineList")
    public DataGridView loadAllStandFineList(StandFileListVo standFineListVo){
        //获取用户session
        //User user = (User)WebUtils.getSession().getAttribute("user");
        IPage<StandFileList> page = new Page<>(standFineListVo.getPage(),standFineListVo.getLimit());
        QueryWrapper<StandFileList> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(standFineListVo.getDocumentName()),"document_name",standFineListVo.getDocumentName());
        standFineListService.page(page,queryWrapper);
        List<StandFileList> records = page.getRecords();
        for (StandFileList record : records) {
            if(null!=record.getSid()){
                Station station = stationService.getById(record.getSid());
                record.setStationName(station.getTitle());
            }
            if (null!=record.getModifyPerson()){
                User user = userService.getById(record.getModifyPerson());
                record.setModifyPersonName(user.getName());
            }
        }
        return new DataGridView(page.getTotal(),page.getRecords());
    }
    //添加公告
    @RequestMapping("addStandFineList")
    public R addStandFineList(StandFileListVo standFineListVo){
        try {
            standFineListVo.setCreateDate(new Date());
            User user = (User)WebUtils.getSession().getAttribute("user");
            standFineListVo.setModifyPerson(user.getId());
            Integer sid = standFineListVo.getSid();
            Station station = stationService.getById(sid);
            List<StandFileList> fileLists = standFineListService.list();
            for (StandFileList fileList : fileLists) {
                Integer listSid = fileList.getSid();
                if(listSid==sid){
                    return R.error().message(station.getTitle()+"站细已存在");
                }
            }
            standFineListService.save(standFineListVo);
            return R.ok().message("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("添加失败");
        }
    }
    //更新公告
    @RequestMapping("updateStandFineList")
    public R updateStandFineList(StandFileListVo standFineListVo){
        try {
            standFineListService.updateById(standFineListVo);
            return R.ok().message("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }
    /**
     * 根据Id 删除
     * */
    @RequestMapping("deleteStandFineList")
    public R deleteById(Integer id){
        try {
            QueryWrapper<FileManage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stand_fileId",id);
            List<FileManage> list = fileManageService.list(queryWrapper);
            List<Integer> ids = new ArrayList<>();
            for (FileManage fileManage : list) {
                Integer fileManageId = fileManage.getId();
                ids.add(fileManageId);
            }
            System.out.println("ids---------------"+ids);
            fileManageService.removeByIds(ids);
            standFineListService.removeById(id);
            return R.ok().message("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }
    /**
     * 查询条件
     * */
    @RequestMapping("loadAllstandFineListForSelect")
    public DataGridView loadAllstandFineListForSelect(){
        List<StandFileList> list = standFineListService.list(null);
        return new DataGridView(list);
    }

    /*站细内容一键同步 将模板同步到站段的站细详情中*/
    @RequestMapping("syncStandFile")
    public R syncStandFile(StandFileList standFileList){
        List<Article> articleList = articleService.list(null);
        QueryWrapper<StandFileList> queryWrapper = new QueryWrapper<>();
        List<StandFileList> standFileLists = standFineListService.list(queryWrapper);
        if(standFileLists.size()==0){
            queryWrapper.eq("stand_status",0);
        }else {
            queryWrapper.eq("stand_status",1);
        }
        for (StandFileList fileList : standFileLists) {
            Integer fileListId = fileList.getId();
            if(fileList.getStandStatus()==0){
                FileManage fileManage = new FileManage();
                for (Article article : articleList) {
                    fileManage.setStandFileid(fileListId);
                    fileManage.setTreeId(article.getId());
                    fileManage.setTreePid(article.getPid());
                    fileManage.setTreeTitle(article.getArticleTitle());
                    fileManage.setTreeContext(article.getArticleContext());
                    fileManage.setOpen(article.getOpen());
                    fileManageService.save(fileManage);
                }
                StandFileList list = standFineListService.getById(fileListId);
                list.setStandStatus(1);
                standFineListService.updateById(list);
            }
        }
        return R.ok().message("同步成功");
    }

    /**
     *加载编辑站细左边的部门树结构Json
     */
    @RequestMapping("loadStandFileManagerLeftJson/{id}")
    public DataGridView loadStandFileManagerLeftJson(@PathVariable("id") Integer id,HttpServletRequest request, StandFileList standFileList){
        QueryWrapper<FileManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stand_fileId",id);
        List<FileManage> list = fileManageService.list(queryWrapper);
        List<TreeNode> treeNodes = new ArrayList<>();
        for (FileManage fileManage : list) {
            Boolean spread = fileManage.getOpen()==1?true:false;
            treeNodes.add(new TreeNodeStand(fileManage.getTreeId(),fileManage.getTreePid(),fileManage.getTreeTitle(),spread,""+fileManage.getId()+""));
        }
        return new DataGridView(treeNodes);
    }

    //添加站细时将使用默认站细名称
    @RequestMapping("changeStandFileName")
    public Map<String , Object> changeStandFileName(Integer sid){
        HashMap<String, Object> map = new HashMap<>();
        if(sid!=null){
            Station station = stationService.getById(sid);
            map.put("documentName",station.getTitle()+"《站细》");
        }else {
            map.put("documentName","");
        }
        return map;
    }

}

